package com.haizhi.crm.sys.auth.model;

import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyijun on 2018/5/16.
 */
@Data
@ApiModel
@NoArgsConstructor
public class ResourceVo {
    private Long id;
    private String name;
    private String remark;
    private Long parentId;
    private String checked;
    private List<ResourceVo> subs = new ArrayList<>();

    public void addSubs(ResourceVo resourceVo) {
        subs.add(resourceVo);
    }

    public ResourceVo(Long id, String name, String remark, Long parentId, String checked) {
        this.id = id;
        this.name = name;
        this.remark = remark;
        this.parentId = parentId;
        this.checked = checked;
    }

    public static List<ResourceVo> buildResourceTree(List<ResourceVo> resourceVos) {
        List<ResourceVo> rootResource = new ArrayList<>();
        Map<Long, ResourceVo> rMap = new LinkedHashMap<>();
        for (ResourceVo rv : resourceVos) {
            if (rv.getParentId() == null) {
                rootResource.add(rv);
            }
            rMap.put(rv.getId(), rv);
        }

        for (ResourceVo rv : resourceVos) {
            if (rv.getParentId() != null && rMap.containsKey(rv.getParentId())) {
                rMap.get(rv.getParentId()).addSubs(rv);
            }
        }
        return rootResource;
    }

    public static List<ResourceVo> buildResourceTreeFromDo(List<ResourceDo> resourceDos) {
        List<ResourceVo> rootResource = new ArrayList<>();
        if (!CollectionUtils.isEmpty(resourceDos)) {
            List<ResourceVo> resourceVos = new ArrayList<>();
            for (ResourceDo rd : resourceDos) {
                ResourceVo rv = new ResourceVo();
                rv.setId(rd.getId());
                rv.setRemark(rd.getRemark());
                rv.setName(rd.getName());
                rv.setParentId(rd.getParentId());
                rv.setChecked("true" );
                resourceVos.add(rv);
            }
            rootResource = buildResourceTree(resourceVos);
        }
        return rootResource;
    }
}
